package light.head.controller.inv;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.inv.InvBillConfingDAO;
import light.head.dao.inv.InvBusinessDAO;
import light.head.dao.inv.InvCommodityItemDAO;
import light.head.dao.inv.InvDepotDAO;
import light.head.dao.inv.InvOrderInfoDAO;
import light.head.dao.inv.InvOrderItemDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.inv.InvDepot;
import light.head.model.inv.InvOrderInfo;
import light.head.model.inv.InvOrderItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_INVORDERINFO)
public class InvOrderInfoController extends SupporterController{
	private InvOrderInfoDAO ioiDAO;
	private InvOrderItemDAO iomDAO;
	private OrganDAO organDAO;
	private InvCommodityItemDAO iciDAO;
	private InvBusinessDAO ibDAO;
	private InvBillConfingDAO ibcfDAO;
	private InvDepotDAO idDAO;
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.INVORDERINFO_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED, Parm.TIME1, Parm.TIME2, Parm.DN,Parm.BN,Parm.TYPE,Parm.CN,Parm.ON);
		if (ioiDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS) {
			InvOrderInfo info = null;
			for (Object o : pb.getResultList()) {
				info = (InvOrderInfo) o;
				info.setItemList(iomDAO.findByIc(info.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.INVORDERINFO_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(code != null){
			InvOrderInfo info = ioiDAO.get(code);
			List<InvOrderItem> list = iomDAO.findByIc(info.getCode());
			info.setItemList(list);
			request.setAttribute(Parm.INVORDERINFO, info);
		}
		return new ModelAndView(Url.INVORDERINFO_EDIT);
	}
	
	@RequestMapping(value = Url.SAVE)
	public void save(InvOrderInfo io, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		if (io == null) {
			print(response, Msg.PARAMETER_ERROR);
			return ;
		}
		// 检查是否有可以保存的明细在保存,至少有一条明细可以保存
		boolean ok = true;
		for (InvOrderItem Item : io.getItemList()) {
			if (null != Item && null != Item.getCount() && null != Item.getCc()) {
				ok = false;
			}
		}
		if (ok) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		if (io.getCode() == null) {
			io.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_ONE));
			io.setCu(cu_code(request));
			io.setCt(new Date());
			io.setOc(cu_organCode(request));
			result = ioiDAO.add(io);
		} else {
			result = ioiDAO.update(io);
		} if (RESULT.SUCCESS == result && io.getItemList().size() > 0) {
			List<InvOrderItem> list = io.getItemList();						//页面上传过来的
			List<InvOrderItem> oldList = iomDAO.findByIc(io.getCode());		//数据库里的
			List<InvOrderItem> deletedList = new ArrayList<InvOrderItem>();	// 存放页面已经删除的
			Boolean yes = null;
			for (InvOrderItem db : oldList) {
				yes = true;
				if (io.getItemList() == null || io.getItemList().size() == 0) {
					deletedList.add(db);
				} else {
					for (InvOrderItem ioi : list) {
						if (null != ioi.getCode() && ioi.getCode().intValue() == db.getCode().intValue()) {
							yes = false;
							break;
						} 
					}
					if (yes) {
						deletedList.add(db);
					}
				}
			}
			// 删除(在数据库中deleted = true)
			for (InvOrderItem ioi : deletedList) {
				ioi.setDeleted(true);
				result = ioiDAO.upd(ioi);
				if (RESULT.SUCCESS != result) {
					throw new Exception("保存失败"); 
				}
			}
			for (InvOrderItem pii : list) {
				if (null == pii.getCode()) {
					if (null != pii.getCount() && null != pii.getCc()) {
						pii.setOic(io.getCode());
						result = ioiDAO.add(pii);
					}
				} else {
					for (InvOrderItem old : oldList) {
						if (pii.getCode().intValue() == old.getCode().intValue()) {
							old.setCc(pii.getCc());
							old.setCount(pii.getCount());
							old.setPrice(pii.getPrice());
							old.setCname(pii.getCname());
							result = ioiDAO.upd(old);
						}
					}
				}
			}
			print(response, "{\"result\":\"success\",\"code\":\""+ io.getCode() +"\"}");
		} else
			print(response, Msg.J_ERROR);
	}
	
	
	@RequestMapping(value = Url.IN)
	public ModelAndView in(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(code != null){
			InvOrderInfo info = ioiDAO.get(code);
			List<InvOrderItem> list = iomDAO.findByIc(info.getCode());
			info.setItemList(list);
			request.setAttribute(Parm.INVORDERINFO, info);
		}
		List<InvDepot> typeList = idDAO.findAll(organDAO.getSonCodeList(cu_organCode(request)));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			for (InvDepot type : typeList){
				result.append("{");
				result.append("\"dname\":\"" + type.getName() +"\",");
				result.append("\"dc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		}
		return new ModelAndView(Url.INVORDERINFO_IN);
	}
	/**
	 * 查询商品
	 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVORDERINFO_AID_INIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == iciDAO.findByMap(oc, map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVORDERINFO_AID_LIST);
	}
	
	/**
	 * 查询供货商
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVORDERINFO_AID_INIT1);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == ibDAO.findByMap(oc, map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVORDERINFO_AID_LIST1);
	}
	
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvOrderInfo de = ioiDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(true);
		if (ioiDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvOrderInfo de = ioiDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(false);
		if (ioiDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@Autowired
	public void setIoiDAO(InvOrderInfoDAO ioiDAO) {
		this.ioiDAO = ioiDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setIomDAO(InvOrderItemDAO iomDAO) {
		this.iomDAO = iomDAO;
	}
	@Autowired
	public void setIciDAO(InvCommodityItemDAO iciDAO) {
		this.iciDAO = iciDAO;
	}
	@Autowired
	public void setIbDAO(InvBusinessDAO ibDAO) {
		this.ibDAO = ibDAO;
	}
	@Autowired
	public void setIbcfDAO(InvBillConfingDAO ibcfDAO) {
		this.ibcfDAO = ibcfDAO;
	}
	@Autowired
	public void setIdDAO(InvDepotDAO idDAO) {
		this.idDAO = idDAO;
	}
	
}
